package com.example.controller;


import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@Controller
public class FileController {

    @GetMapping("/upload")
    public String upload() {
        return "upload";
    }

    @PostMapping("/upload")
    public String uploadfile(MultipartFile[] files, Model model) {

        //foreach遍历多文件
        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                //定义文件跟路径
                String dirPath = "F:/IDEA/test/";
                //获取遍历文件带后缀的文件名
                String fileName = file.getOriginalFilename();
                //整合路径跟文件名
                File file1 = new File(dirPath + fileName);
                //如果图片存在
                if (file1.exists()) {
                    model.addAttribute("thisMsg", "文件存在");
                    return "upload";
                }
                try {
                    //文件转换为二进制流
                    file.transferTo(file1);
                } catch (Exception e) {
                    model.addAttribute("thisMsg", "上传失败");
                }
            } else {
                model.addAttribute("thisMsg", "文件为空");
            }
        }


        return "upload";
    }


    @GetMapping("/download")
    public String download(Model model) {
        String dirPath = "F:/IDEA/test/";
        File file = new File(dirPath);
        String[] files = file.list();
        model.addAttribute("files", files);
        return "download";
    }


    @GetMapping("/downloadfile")
    public ResponseEntity<byte[]> downloadFile(String filename) throws IOException {
        String dirPath = "F:/IDEA/test/";
        File file = new File(dirPath + File.separator + filename);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode(filename, "UTF-8"));
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), httpHeaders, HttpStatus.OK);
    }
}
